import { mxCell } from 'mxgraph'
import { Col, Divider, Row, Select, Space, Input, TreeSelect } from 'antd'
import editOutlined from '@iconify/icons-ant-design/edit-outlined'
import IconButton from '@/components/Icon'
import { useEffect, useRef, useState } from 'react'
import { getTslServiceList, getTslPropertyList, stationAndDeviceList } from '@/api/base'
import * as DSApi from '@/api/dataSource'
import EditorExecutor from '@/executor/EditorExecutor'
import { createPortal } from 'react-dom'
import DataSourceDialog from '@/components/Dialogs/DataSourceDialog'

interface IDataSettingProps {
  cell: mxCell | undefined
}
// 设备的别名
const DeviceAliasMap = {
  AM: '电表',
  EDGE: '终端',
  POC: '并网点'
}
export default function DataSetting(props: IDataSettingProps) {
  // 设备类型下拉列表
  const [deviceTypeList, setDeviceTypeList] = useState<any[]>([])
  // 已选择的设备类型
  const [deviceType, setDeviceType] = useState('')
  // 所有的设备列表
  const allDeviceList = useRef<any[]>([])
  // 设备列表
  const [deviceList, setDeviceList] = useState<any[]>([])
  // 当前选中的设备Code
  const [deviceCode, setDeviceCode] = useState('')
  // 物模型数据
  const [tslPropsTree, setTslPropsTree] = useState<any>([])
  // 缓存所有的物模型数据
  const tslPropertyMap = useRef<{ [key: string]: any }>({})
  // 当前的绑定变量
  const [dataName, setDataName] = useState('')
  // 数据源设置窗口可见状态
  const [dsDialogOpen, setDsDialogOpen] = useState(true)

  // 当设备类型发生变化
  const onDeviceTypeChange = async (v: any) => {
    setDeviceType(v)
    // 筛选设备类别
    const list = allDeviceList.current
      .filter((item: any) => item.productCategoryCode == v)
      .map((item) => {
        return {
          label: item.deviceName,
          value: item.deviceCode
        }
      })
    setDeviceList(list)
    setDataName('')
    const tslTree = await getTslData(v)
    setTslPropsTree(tslTree)
  }

  // 获取物模型数据
  const getTslData = async (deviceType: string) => {
    const cache = tslPropertyMap.current
    if (!cache[deviceType]) {
      // 如果数据不存在
      const device = allDeviceList.current.find(
        (device) => device.productCategoryCode == deviceType
      )
      if (device) {
        const categorys: any[] = await getTslServiceList(device.productId)
        const properties: any[] = await getTslPropertyList(device.productId)
        const ops = properties.filter((n) => n.propertyType == 'output')
        const tree = categorys.map((item) => {
          return {
            title: item.serviceName,
            value: item.serviceCode,
            selectable: false,
            key: item.serviceCode,
            children: ops
              .filter((n) => n.tslServiceId == item.id)
              .map((n) => {
                return {
                  title: n.propertyName,
                  value: n.propertyCode,
                  key: n.propertyCode
                }
              })
          }
        })

        // 保存到缓存中
        cache[deviceType] = tree
        return tree
      }
    } else {
      return cache[deviceType]
    }
  }

  // 当设备发生变化
  const onDeviceChange = (v: string) => {
    setDeviceCode(v)
    EditorExecutor.setAttrValue('deviceCode', v)
  }

  // 当绑定变量发生变化
  const onDataNameChange = (v: string) => {
    setDataName(v)
    EditorExecutor.setAttrValue('dataName', v)
  }

  //获取数据源列表
  const getDataSourceList = async () => {
    const result = await DSApi.getDataSourcePage({
      pageNo: 1,
      pageSize: 50
    })
  }
  useEffect(() => {
    //@ts-ignore
    const { stationId } = EditorExecutor.fileMeta

    if (deviceTypeList.length == 0 && stationId) {
      stationAndDeviceList(stationId).then((data: any[]) => {
        allDeviceList.current = data
        const set = new Set()
        data.forEach((item) => {
          if (item.productCategoryCode) {
            set.add(item.productCategoryCode)
          }
        })
        const list = Array.from(set).map((item) => {
          return {
            //@ts-ignore
            label: DeviceAliasMap[item] ? DeviceAliasMap[item] : item,
            value: item
          }
        })
        // 设备类型类别
        setDeviceTypeList(list)
        if (list.length > 0) {
          const type = list[0].value
          setDeviceType(type as string)
          onDeviceTypeChange(type)
        }
      })
    }
  }, [])

  // 当选中的图元发生变化是
  useEffect(() => {
    if (props.cell) {
      const value = props.cell.value
      if (mxUtils.isNode(value, 'object')) {
        let code = (value as Element).getAttribute('deviceCode')
        const dName = (value as Element).getAttribute('dataName')
        console.log(code)
        if (code) {
          const type = code?.split('_')[0].toUpperCase()
          setDeviceType(type)
          onDeviceTypeChange(type)
        } else {
          code = ''
        }
        setDataName(dName || '')
        setDeviceCode(code)
      } else {
        setDeviceType('')
        setDeviceCode('')
        setDataName('')
      }
    }
  }, [props.cell])

  return (
    <>
      <Space direction="vertical" size="small" style={{ display: 'flex' }}>
        <Row>
          <Col span={10} className="label">
            数据源
          </Col>
        </Row>
        <Row gutter={2}>
          <Col span={18}>
            <Select
              options={[
                {
                  label: '数据源1',
                  value: '1'
                }
              ]}
              value={'1'}
              defaultActiveFirstOption={true}
              className="h-26px w-100% font-size-12px"
              onChange={(v) => {}}
            />
          </Col>
          <Col>
            <IconButton
              icon={editOutlined}
              tip="编辑"
              className="h-24px w-24px"
              onClick={() => setDsDialogOpen(true)}
            />
          </Col>
        </Row>
        <Divider className="mt-3px mb-0px" />
        <Row>
          <Col span={10} className="label">
            设备
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={8}>设备类型</Col>
          <Col span={16}>
            <Select
              options={deviceTypeList}
              value={deviceType}
              className="h-26px w-100% font-size-12px"
              onChange={(v: string) => {
                onDeviceTypeChange(v)
              }}
            />
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={8}>设备名称</Col>
          <Col span={16}>
            <Select
              options={deviceList}
              value={deviceCode}
              className="h-26px w-100% font-size-12px"
              onChange={(v: string) => {
                onDeviceChange(v)
              }}
            />
          </Col>
        </Row>
        <Row>
          <Col span={8}>设备Code</Col>
          <Col span={16}>
            <Input.TextArea disabled={true} value={deviceCode} className="w-100%"></Input.TextArea>
          </Col>
        </Row>
        <Divider className="mt-3px mb-0px" />
        <Row>
          <Col span={10} className="label">
            绑定
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={8}>变量</Col>
          <Col span={16}>
            <TreeSelect
              className="w-100% h-26px"
              dropdownStyle={{ minWidth: '200px' }}
              showSearch
              allowClear
              treeData={tslPropsTree}
              value={dataName}
              onChange={(value) => {
                onDataNameChange(value)
              }}
            />
          </Col>
        </Row>
      </Space>
      {dsDialogOpen &&
        createPortal(
          <DataSourceDialog
            onClose={() => setDsDialogOpen(false)}
            onOk={() => {
              getDataSourceList()
            }}
          ></DataSourceDialog>,
          document.body
        )}
    </>
  )
}
